// request.js
import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus'; // 导入 ElLoading 和 ElMessage
import { getToken } from '@/utils/auth';

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '/api',
  timeout: 30000,
});

let requestCount = 0;
let loadingInstance = null;

function showLoading() {
  if (requestCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.1)'
    });
  }
  requestCount++;
}

function hideLoading() {
  requestCount--;
  if (requestCount <= 0 && loadingInstance) {
    loadingInstance.close();
    loadingInstance = null;
  }
}

service.interceptors.request.use(
  (config) => {
    showLoading(); // 显示 loading
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    hideLoading(); // 失败时隐藏 loading
    ElMessage.error('请求失败，请检查网络');
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    hideLoading(); // 成功时隐藏 loading
    // 处理响应...
    return response.data;
  },
  (error) => {
    hideLoading(); // 错误时隐藏 loading
    ElMessage.error('请求失败，请重试');
    return Promise.reject(error);
  }
);

export default service;